import json
import logging

import aiohttp

from src.application.payment.interfaces import BaseApi

logger = logging.getLogger(__name__)


class PaymentAPIImpl(BaseApi):
    def __init__(self, api_token: str, shop_id: str, base_url=None):
        self.api_token = api_token
        self.base_url = base_url
        self.session = aiohttp.ClientSession()
        self.shop_id = shop_id
        self.session.headers.update(
            {
                "Content-Type": "application/json;charset=utf-8",
                "Authorization": f"Bearer {self.api_token}",
                "User-Agent": "paypalych-connector",
            }
        )

    async def send_signed_request(self, http_method: str, url_path: str, payload=None):
        if payload is None:
            payload = {}
        url = self.base_url + url_path
        params = {"url": url, "data": json.dumps(payload)}
        logger.debug("payload:" + json.dumps(payload))
        response = await self._dispatch_request(http_method)(**params)

        try:
            data = await response.json()
        except ValueError:
            data = await response.text()

        if response.status != 200 or not data.get("success"):
            logger.exception(data)
            logger.exception(json.dumps(payload))
            logger.exception(response.url)
            return False

        return data

    def _dispatch_request(self, http_method: str):
        return {
            "GET": self.session.get,
            "DELETE": self.session.delete,
            "PUT": self.session.put,
            "POST": self.session.post,
        }.get(http_method, "GET")
